import { getInfo, login, logout, modifyPassword, verifyPassword } from '@/api/rest/user'
import { getToken, removeToken, setToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import rs from 'jsrsasign'
import moment from 'moment/moment'

const STATE = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  permissions: [],
  menus: [],
  roleMap: {},
  permissionMap: {},
  modifyPassword: false,
  lastDateTime: null,
  lockScreenTime: null,
  lockScreen: false,
  publicKey: rs.KEYUTIL.getKey(
    '-----BEGIN PUBLIC KEY-----\n' +
    process.env.VUE_APP_RSA_PUBLIC_KEY +
    '\n-----END PUBLIC KEY-----'
  )
}

const getters = {
  modifyPassword(state) {
    return state.modifyPassword || false
  },
  publicKey(state) {
    return state.publicKey
  }
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus
  },
  SET_ROLE_MAP: (state, roleMap) => {
    state.roleMap = roleMap
  },
  SET_PERMISSION_MAP: (state, permissionMap) => {
    state.permissionMap = permissionMap
  },
  TOGGLE_MODIFY_PASSWORD: (state, visible) => {
    state.modifyPassword = visible
  },
  SET_LAST_DATE_TIME: (state, lastDateTime) => {
    state.lastDateTime = lastDateTime
    localStorage.setItem('lastDateTime', lastDateTime)
  },
  SET_LOCK_SCREEN_TIME: (state, lockScreenTime) => {
    state.lockScreenTime = lockScreenTime
    localStorage.setItem('lockScreenTime', lockScreenTime)
  },
  SET_LOCK_SCREEN: (state, lockScreen) => {
    state.lockScreen = lockScreen
    localStorage.setItem('lockScreen', lockScreen)
  }
}

const actions = {
  // user login
  login({ commit, state }, userInfo) {
    const { username } = userInfo
    const password = rs.KJUR.crypto.Cipher.encrypt(
      userInfo.password,
      state.publicKey
    )
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password })
        .then(() => {
          const token = 'ADMIN-TOKEN'
          commit('SET_TOKEN', token)
          commit('SET_LAST_DATE_TIME', moment.now())
          commit('SET_LOCK_SCREEN', false)
          setToken(token)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // sso login
  oauthLogin({ commit }) {
    return new Promise((resolve, reject) => {
      const token = 'ADMIN-TOKEN'
      commit('SET_TOKEN', token)
      setToken(token)
      resolve()
    })
  },

  // get user info
  getInfo({ commit }, sysComponent) {
    return new Promise((resolve, reject) => {
      getInfo(sysComponent)
        .then((response) => {
          const { data } = response

          if (!data) {
            reject(Error('Verification failed, please Login again.'))
          }

          const {
            roles,
            permissions,
            menus,
            name,
            avatar,
            introduction,
            loginOperation
          } = data

          // roles must be a non-empty array
          if (!roles || roles.length <= 0) {
            // reject('getInfo: roles must be a non-null array!')
            // TODO 框架限制不返回 roles 会各种报错 暂时写死一个
            data.roles = ['_']
            commit('SET_ROLES', data.roles)
          } else {
            commit('SET_ROLES', roles)
          }

          commit('SET_PERMISSIONS', permissions)
          commit('SET_MENUS', menus)
          commit('SET_NAME', name)
          commit('SET_AVATAR', avatar)
          commit('SET_INTRODUCTION', introduction)

          if (~~loginOperation === 1) {
            commit('TOGGLE_MODIFY_PASSWORD', true)
          } else {
            commit('TOGGLE_MODIFY_PASSWORD', false)
          }

          if (roles) {
            const roleMap = {}
            roles.forEach((r) => {
              roleMap[r] = true
            })
            commit('SET_ROLE_MAP', roleMap)
          }

          if (permissions) {
            const permissionMap = {}
            permissions.forEach((p) => {
              permissionMap[p] = true
            })
            commit('SET_PERMISSION_MAP', permissionMap)
          }
          resolve(data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  verifyUserPassword({ commit, state }, data) {
    const _password = rs.KJUR.crypto.Cipher.encrypt(
      data.password,
      state.publicKey
    )

    return new Promise((resolve, reject) => {
      verifyPassword(_password)
        .then((res) => {
          if (res.success) {
            commit('SET_LAST_DATE_TIME', moment.now())
            commit('SET_LOCK_SCREEN', false)
            resolve(true)
          } else {
            reject(false)
          }
        })
        .catch(() => {
          reject(false)
        })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          resetRouter()

          // reset visited views and cached views
          // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
          dispatch('tagsView/delAllViews', null, { root: true })

          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = `${role}-token`

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, {
      root: true
    })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  },

  toggleModifyPassword({ commit }, visible) {
    commit('TOGGLE_MODIFY_PASSWORD', visible)
  },

  modifyPassword({ commit, state }, data) {
    const postForm = {
      originalPassword: rs.KJUR.crypto.Cipher.encrypt(
        data.originalPassword,
        state.publicKey
      ),
      newPassword: rs.KJUR.crypto.Cipher.encrypt(
        data.newPassword,
        state.publicKey
      ),
      confirmPassword: rs.KJUR.crypto.Cipher.encrypt(
        data.confirmPassword,
        state.publicKey
      )
    }
    return new Promise((resolve, reject) => {
      modifyPassword(postForm)
        .then((resp) => {
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  setLastDateTime({ commit }, lastDateTime) {
    commit('SET_LAST_DATE_TIME', lastDateTime)
  },
  setLockScreenTime({ commit }, lockScreenTime) {
    commit('SET_LOCK_SCREEN_TIME', lockScreenTime)
  },
  setLockScreen({ commit }, lockScreen) {
    commit('SET_LOCK_SCREEN', lockScreen)
  }
}

export default {
  namespaced: true,
  getters,
  state: STATE,
  mutations,
  actions
}
